package com.zzy.filter;

import com.zzy.model.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/** 
 * 不允许直接访问jsp 
 * 所有对jsp的直接访问，跳转到首页面 
 * @author zzy 
 * 
 */  
public class jspFilter implements Filter {
	ServletContext context;
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       
    	
    	HttpServletRequest httpServletRequest = (HttpServletRequest) request;
       HttpServletResponse httpServletResponse = (HttpServletResponse) response;
       String url = httpServletRequest.getRequestURI();
       HttpSession session = httpServletRequest.getSession();
       
        User p = new User();
        p = (User) session.getAttribute("user");

        if( url.endsWith("index") ){//暂时只处理首页的


			/*(url.endsWith(".do") || url.endsWith(".jsp")) &&
					( !url.endsWith("index")
									&& !url.endsWith("login")
									&& !url.contains("test")
									&& !url.contains("test") )*/

          if(p==null || p.getId()==null){
		    	String paths = httpServletRequest.getContextPath();
				String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ paths + "/";
			  	//request.getRequestDispatcher(basePath+"index.jsp").forward(request, response);
				httpServletResponse.sendRedirect(basePath+"login");
		    	
		    }

        }
        
        chain.doFilter(request, response); 
        
        
        
    }

	public void destroy() {
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		context  = filterConfig.getServletContext();
	}  
  
  
}   